/**
 * 交易模块
 */
(function(window) {
    'use strict';
    
    /**
     * 结算账单
     */
    function settleBill(cartItems) {
        return $.ajax({
            url: '/api/settle',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(cartItems)
        });
    }
    
    /**
     * 获取交易记录列表
     */
    function getTransactions(page, searchNo) {
        let url = `/api/transactions?page=${page}`;
        if (searchNo) {
            url += `&search_no=${searchNo}`;
        }
        return $.ajax({
            url: url,
            type: 'GET',
            dataType: 'json'
        });
    }
    
    /**
     * 获取交易明细
     */
    function getTransactionDetails(transactionId) {
        return $.ajax({
            url: `/api/transactions/${transactionId}/details`,
            type: 'GET',
            dataType: 'json'
        });
    }
    
    /**
     * 加载交易记录
     */
    function loadTransactions() {
        const currentLang = window.currentLang || 'zh';
        const trans = window.translations?.[currentLang];
        const page = 1;
        const searchNo = $('#transactionSearch').val();
        
        // 显示加载状态
        $('#transactionTable tbody').html('<tr><td colspan="6" class="text-center">' + (trans?.loading || '加载中...') + '</td></tr>');
        
        // 获取交易记录
        getTransactions(page, searchNo).done(function(response) {
            const transactions = response.transactions || [];
            const totalPages = response.total_pages || 1;
            const currentPage = response.current_page || 1;
            
            // 渲染交易记录表格
            const transactionTable = $('#transactionTable').find('tbody');
            transactionTable.empty();
            
            if (!transactions || transactions.length === 0) {
                transactionTable.html('<tr><td colspan="6" class="text-center">' + (trans?.noTransactions || '暂无交易记录') + '</td></tr>');
            } else {
                transactions.forEach(function(transaction) {
                    const row = `<tr>
                        <td>${transaction.transaction_no}</td>
                        <td>${transaction.transaction_time}</td>
                        <td>${transaction.total_amount}</td>
                        <td>${transaction.status}</td>
                        <td>${transaction.operator}</td>
                        <td>
                            <button class="btn btn-sm btn-primary view-transaction" data-id="${transaction.id}">查看明细</button>
                            <button class="btn btn-sm btn-secondary print-transaction" data-id="${transaction.id}">打印</button>
                        </td>
                    </tr>`;
                    transactionTable.append(row);
                });
                
                // 绑定查看明细按钮事件
                $('.view-transaction').click(function() {
                    const transactionId = $(this).data('id');
                    viewTransactionDetails(transactionId);
                });
                
                // 绑定打印按钮事件
                $('.print-transaction').click(function() {
                    const transactionId = $(this).data('id');
                    printTransaction(transactionId);
                });
            }
            
            // 更新分页信息
            $('#pageInfo').text(`${currentPage} 页 共 ${totalPages} 页`);
            $('#prevPage').prop('disabled', currentPage <= 1);
            $('#nextPage').prop('disabled', currentPage >= totalPages);
            
        }).fail(function(xhr, status, error) {
            console.error('获取交易记录时发生错误:', error);
            $('#transactionTable tbody').html('<tr><td colspan="6" class="text-center">' + (trans?.loadError || '加载失败') + '</td></tr>');
        });
    }
    
    /**
     * 查看交易明细
     */
    function viewTransactionDetails(transactionId) {
        // 实现查看交易明细的逻辑
        console.log('查看交易明细:', transactionId);
    }
    
    /**
     * 打印交易单
     */
    function printTransaction(transactionId) {
        // 实现打印交易单的逻辑
        console.log('打印交易单:', transactionId);
    }
    
    // 暴露API
    window.TransactionModule = {
        settleBill: settleBill,
        getTransactions: getTransactions,
        getTransactionDetails: getTransactionDetails,
        loadTransactions: loadTransactions,
        viewTransactionDetails: viewTransactionDetails,
        printTransaction: printTransaction
    };
    
})(window);

